/*******************************************************************************
 * Copyright 2011 WaTho
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.wathoserver.android.dragoid.api;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Element;

import de.wathoserver.android.dragoid.R;

import android.app.Activity;
import android.widget.TextView;

/**
 * Benutzerinfo "rechts oben" mit Name, Punkte, Gold und Rubine.
 * 
 * @author watho
 * 
 */
public class UserInfo {
	private String userName = "";
	private String points = "";
	private String money = "";
	private String ruby = "";
	private Pattern p;

	public UserInfo() {
		p = Pattern
				.compile("Name:\\s*(\\w*)\\s*Punkte:\\s*([0-9.]*)\\sGold:\\s*([0-9.]*)\\s*(\\d*).*");
	}

	public String getUserName() {
		return userName;
	}

	public String getPoints() {
		return points;
	}

	public String getMoney() {
		return money;
	}

	public String getRuby() {
		return ruby;
	}

	/**
	 * Parst den UserInfo-Block im Header.
	 * 
	 * <div style=
	 * "position: absolute; left: 809px; top: 7px; text-align: left; font-weight: bold; color: rgb(61, 52, 43);"
	 * id="userinfo"> Name: watho<br>
	 * Punkte: 4.002<br>
	 * Gold: 69.324<br>
	 * <a style=
	 * "color: rgb(61, 52, 43); background: none repeat scroll 0% 0% transparent; padding: 0px;"
	 * href="?t=einstellungen&amp;tab=2">Rubine:</a> 59<br>
	 * </div>
	 * 
	 * @param div
	 *            mit id="userinfo"
	 * 
	 */
	public void parseUserStatus(Element userInfo) {
		if (userInfo == null) {
			return;
		}
		// Name: watho Punkte: 4.002 Gold: 69.324 59
		String text = userInfo.getTextNormalize();
		Matcher m = p.matcher(text);
		if (m.matches() && m.groupCount() == 4) {
			userName = m.group(1);
			points = m.group(2);
			money = m.group(3);
			ruby = m.group(4);
		}
	}

	/**
	 * Wird von Activity aufgerufen um Werte in der Ansicht zu aktualisieren.
	 */
	public void updateUI(Activity activity) {
		TextView tv = (TextView) activity.findViewById(R.id.user);
		tv.setText(userName);
		tv = (TextView) activity.findViewById(R.id.points);
		tv.setText(String.format("Punkte: %s", points));
		tv = (TextView) activity.findViewById(R.id.money);
		tv.setText(String.format("Gold: %s", money));
		tv = (TextView) activity.findViewById(R.id.ruby);
		tv.setText(String.format("Rubine: %s", ruby));
	}

}
